package handle

import (
	"api-gateway/basic/config"
	__ "api-gateway/basic/proto"
	"api-gateway/handle/request"
	"net/http"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
)

func Login(c *gin.Context) {
	var req request.UserLogin
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":  http.StatusBadRequest,
			"msg":   "参数错误",
			"error": err.Error(),
		})
		return
	}

	login, err := config.Discount.UserLogin(c, &__.UserLoginReq{
		Phone:    req.Phone,
		Password: req.Password,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":  http.StatusInternalServerError,
			"msg":   err.Error(),
			"error": err.Error(),
		})
		return
	}
	token, err := gojwt.NewJWT(config.TOKEN_Key).CreateToken(gojwt.CustomClaims{
		ID: uint(login.UserId),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Hour * 24 * 7).Unix(),
		},
	})

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "OK",
		"Data": token,
	})

}
